package com.kgc.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.kgc.common.result.ResultCode;
import com.kgc.service.base.exception.HpitException;
import com.kgc.vod.service.VideoService;
import com.kgc.vod.utils.AliyunVodSDKUtils;
import com.kgc.vod.utils.PropUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@Service
public class VideoServiceImpl implements VideoService {

    private PropUtil propUtil;

    public VideoServiceImpl(PropUtil propUtil) {
        this.propUtil = propUtil;
    }
    @Override
    public String upload(MultipartFile file) {
        try {
            String fileName=file.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(propUtil.getKeyid(),
                    propUtil.getKeysecret(), title, fileName, inputStream);
            request.setApiRegionId("cn-shanghai");
            UploadVideoImpl uploader=new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            if (!response.isSuccess()) {
                throw new HpitException(ResultCode.VIDEO_UPLOAD_ALIYUN_ERROR);
            }
            return response.getVideoId();

        } catch (IOException e) {
            e.printStackTrace();
            throw new HpitException(ResultCode.VIDEO_UPLOAD_ALIYUN_ERROR);
        }

    }

    @Override
    public void delVideoById(String id) {
        try {
            // 创建request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            // 获取client对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(propUtil.getKeyid(), propUtil.getKeysecret());
            // 设置删除id
            request.setVideoIds(id);
            // 执行删除获取结果
            client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new HpitException(ResultCode.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }
}
